package com.sondon.dev_soceket.tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;

/**
 * 
 * @Project : Java_C_Socket_Maven
 * @Package : com.sondon.tcpip
 * @Class : TCPEchoClient.java
 * @Company 广州讯动网络科技有限公司
 * @Author : 蔡文锋
 * @DateTime：2015年4月13日 下午4:06:04
 * @Blog：http://blog.csdn.net/caiwenfeng_for_23
 * @Description : { TCP客户端 }
 */
public class TCPClient {

	public static void main(String[] args) throws IOException {
		byte[] data = "socket  testing".getBytes();
		// 使用指定的服务器和端口创建Socket
		Socket socket = new Socket("127.0.0.1", 8877);
		// 输入/输出
		InputStream in = socket.getInputStream();
		OutputStream out = socket.getOutputStream();
		// 发送数据
		out.write(data);

		int totalBytesLength = 0;
		int bytesRcvd;

		while (totalBytesLength < data.length) {
			// 阻塞等待服务器端的返回
			if ((bytesRcvd = in.read(data, totalBytesLength, data.length
					- totalBytesLength)) == -1) {
				throw new SocketException("Connection closed prematurely");
			}
			totalBytesLength += bytesRcvd;
		}
		System.out.println("Received:" + new String(data));
		// 3.关闭
		socket.close();
	}
}
